package com.njegovanobradovic.pages.admin;

import java.io.File;

import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.upload.services.UploadedFile;

import com.njegovanobradovic.entities.Page;
import com.njegovanobradovic.entities.Slide;
import com.njegovanobradovic.so.GetAll;
import com.njegovanobradovic.so.Save;

public class AddSlide {
	@Inject
	private Save<Slide> saveSlide;
	@Property
    private UploadedFile file;
	@Property
	private String alt;
	@Property
	private boolean active;
	@Property
	private int orderNum;
	@Inject
	private GetAll<Slide> getAllSlides;
	
	@SuppressWarnings("unused")
	private void onActivate(){
		try {
			getAllSlides.setSearchForType(Slide.class);
			orderNum = getAllSlides.execute().size()+1;
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@CommitAfter
    public Object onSuccess(){
    	try {
            File copied = new File("src/main/webapp/layout/img/" + file.getFileName());
            file.write(copied);
            Slide slide = new Slide();
            slide.setSlideTitle(file.getFileName());
            slide.setAlt(alt);
            slide.setActive(active);
            slide.setOrderNum(orderNum);
            slide.setSrc("layout/img/" + file.getFileName());
            saveSlide.setObject(slide);
            saveSlide.execute();
            return AllSlides.class;
		} catch (Exception e) {
			return null;
		}
    }
	
}
